package com.wtb.javatool.service.impl;

import com.wtb.javatool.dao.EvaluationMapper;
import com.wtb.javatool.entity.Evaluation;
import com.wtb.javatool.service.EvaluationService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class EvaluationServiceImpl implements EvaluationService {


    private final EvaluationMapper evaluationMapper;

    public EvaluationServiceImpl(EvaluationMapper evaluationMapper) {
        this.evaluationMapper = evaluationMapper;
    }


    /**
     * 根据提交记录id 来插入或者更新评论表中的内容
     *
     * @param submissionIds  提交记录id列表
     * @param score          分数
     * @param comment        评论内容
     * @param creatorId      评论人id
     * @param createTime     评论时间
     * @param evaluationType 评论类型
     */
    public void insertOrUpdateEvaluations(List<Long> submissionIds, Double score, String comment, Long creatorId, Date createTime, Integer evaluationType) {
        List<Map<String, Object>> existingRecords = evaluationMapper.findEvaluationsBySubmissionIdsAndType(submissionIds, evaluationType);

        // 2. 将已存在的记录转换为 submissionId -> recordId 的映射
        Map<Long, Long> submissionIdToRecordId = existingRecords.stream()
                .collect(Collectors.toMap(
                        record -> (Long) record.get("submissionId"),
                        record -> (Long) record.get("evaluationId")
                ));

        // 3. 分离需要插入和更新的记录
        List<Evaluation> evaluationsToInsert = new ArrayList<>();
        List<Evaluation> evaluationsToUpdate = new ArrayList<>();

        for (Long submissionId : submissionIds) {
            Evaluation evaluation = new Evaluation();
            evaluation.setSubmissionId(submissionId);
            evaluation.setScore(score);
            evaluation.setComment(comment);
            evaluation.setCreatorId(creatorId);
            evaluation.setCreateTime(createTime);
            evaluation.setEvaluationType(evaluationType);

            if (submissionIdToRecordId.containsKey(submissionId)) {
                // 如果记录已存在，设置 ID 用于更新
                evaluation.setEvaluationId(submissionIdToRecordId.get(submissionId));
                evaluationsToUpdate.add(evaluation);
            } else {
                // 如果记录不存在，添加到插入列表
                evaluationsToInsert.add(evaluation);
            }
        }

        // 4. 批量插入新记录
        if (!evaluationsToInsert.isEmpty()) {
            evaluationMapper.batchInsertEvaluations(evaluationsToInsert);
        }

        // 5. 批量更新已存在的记录
        if (!evaluationsToUpdate.isEmpty()) {
            evaluationMapper.batchUpdateEvaluations(evaluationsToUpdate);
        }
    }
}
